package com.lc.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lc.usercenter.common.BaseResponse;
import com.lc.usercenter.common.ErrorCode;
import com.lc.usercenter.common.ResultUtils;
import com.lc.usercenter.exception.BusinessException;
import com.lc.usercenter.model.domain.User;
import com.lc.usercenter.model.domain.request.UserLoginRequest;
import com.lc.usercenter.model.domain.request.UserRegisterRequest;
import com.lc.usercenter.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

import static com.lc.usercenter.constant.UserConstant.ADMIN_ROLE;
import static com.lc.usercenter.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 功能：用户管理控制器
 * 作者：lc
 * 日期：2024/11/21 15:29
 */
@RestController
@RequestMapping("/user")
@CrossOrigin(origins = {"http://localhost3000"},allowCredentials = "true")
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping("/code")
    public BaseResponse<Boolean> sendCode(@RequestParam("phone") String phone) {
        if (phone == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请输入手机号码");
        }
        boolean result = userService.sendCode(phone);
        return ResultUtils.success(result);

    }

    /**
     * 用户注册
     *
     * @param userRegisterRequest 用户注册请求实体
     * @return 用户id
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest
    ,@RequestParam("validCode") String validCode) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String planeCode = userRegisterRequest.getPlanetCode();
        String phone = userRegisterRequest.getPhone();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, planeCode,phone,validCode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long result = userService.userRegister(userRegisterRequest,validCode);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest 用户登录请求实体
     * @param request          请求体
     * @return user对象
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    /**
     * 用户注销
     *
     * @param request 请求头
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> logout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Integer logout = userService.logout(request);
        return ResultUtils.success(logout);
    }

    /**
     * 用户查询
     *
     * @param username 用户名
     * @param request  请求体
     * @return 用户列表
     */
    @GetMapping("/search")
    public BaseResponse<List<User>> searchUsers(String username, HttpServletRequest request) {
        // 仅供管理请求
        if (isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("userName", username);
        }
        List<User> userList = userService.list(queryWrapper);
        List<User> list = userList.stream().map(user -> userService.getSafatyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(list);

    }

    /**
     * 用户删除
     *
     * @param id      用户id
     * @param request 请求体
     * @return boolean
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUsers(@RequestBody long id, HttpServletRequest request) {
        if (isAdmin(request) || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean isDelete = userService.removeById(id);
        return ResultUtils.success(isDelete);
    }

    /**
     * 是否为管理员
     *
     * @param request 请求体
     * @return boolean
     */

    private boolean isAdmin(HttpServletRequest request) {
        // 仅供管理请求
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        return user != null && !user.getUserRole().equals(ADMIN_ROLE);
    }
}
